﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using ERPServices;
using SilverlightApplication4.ServiceReference1;
using System.Collections.Generic;
using System.Windows.Threading;

namespace SilverlightApplication4.Util
{
    public delegate void GenerateFunc(object sender, EventArgs e);
    public enum InitType
    {
        All = 0,
        Binding = 1,
        DataSource = 2
    }

    public class AppUtil
    {
        IERPModule module;

        public AppUtil(IERPModule _module)
        {
            module = _module;
        }

        public void InitControls(FrameworkElement element, InitType type)
        {
            if (element is TextBox && ((Control)element).IsTabStop == false)
            {
                ((Control)element).Background = new SolidColorBrush(Color.FromArgb(255, 220, 220, 220));
            }

            if(type == InitType.All && element is Control)
                module.lstElements.Add((Control)element);

            if (element is TextBox || element is ComboBox || element is DatePicker || element is DataGrid)
            {
                if(((Control)element).IsTabStop == true)
                    module.lstIndexControls.Add((Control)element);
            }

            if (element.Tag != null && String.IsNullOrEmpty(element.Tag.ToString()) == false)
            {

                String TextID = String.Empty;
                String BDColumn = String.Empty;
                String BDTable = String.Empty;
                String BSValueColumn = String.Empty;
                String BSDisplayColumn = String.Empty;
                String BSTable = String.Empty;
                String BSColumns = String.Empty;
                String tipsTag = String.Empty;
                String ControlDisplayTag = String.Empty;
                bool isAllowNull = true;

                if (element is DataGrid)
                {
                    if(type == InitType.All)
                        InitGridColumn((DataGrid)element);
                }
                else
                    GetBusinessTag(element.Tag.ToString(), out TextID, out BDColumn, out BDTable, out BSValueColumn, out BSDisplayColumn, out BSColumns, out BSTable, out tipsTag, out ControlDisplayTag, out isAllowNull);


                

                if (type == InitType.All || type == InitType.Binding)
                {
                    if (String.IsNullOrEmpty(BDColumn) == false && String.IsNullOrEmpty(BDTable) == false)
                    {
                        Object objSource = module.GetObject(BDTable);
                        if (objSource != null)
                            SetBinding(element, objSource, BDColumn);

                        SetDisplayData(element);
                    }
                }

                if (type == InitType.All || type == InitType.DataSource)
                {
                    if (element is Selector && String.IsNullOrEmpty(BSTable) == false)
                        SetDataSource((Selector)element, BSValueColumn, BSDisplayColumn, BSColumns, BSTable);
                }
            }

            int iChildCount = VisualTreeHelper.GetChildrenCount(element);
            for (int i = 0; i < iChildCount; i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(element, i);
                if (child != null && child is FrameworkElement)
                    InitControls((FrameworkElement)child, type);
            }

            if (type == InitType.All)
            {
                element.GotFocus += element_GotFocus;
                element.LostFocus += element_LostFocus;
                element.KeyDown +=element_KeyDown;
            }
        }

        void InitGridColumn(DataGrid grid)
        {
            if (grid.Tag == null || String.IsNullOrEmpty(grid.Tag.ToString())) return;
            String[] arrs = grid.Tag.ToString().Split('|');
            foreach (String strCol in arrs)
            {
                if (String.IsNullOrEmpty(strCol)) continue;

                String[] cols = strCol.Split(',');

                if (cols.Length >= 2)
                {
                    DataGridTextColumn col = new DataGridTextColumn();
                    col.Header = cols[1];
                    col.Binding = new Binding(cols[0]);
                    col.IsReadOnly = true;

                    grid.Columns.Add(col);
                }
            }
        }

        void element_LostFocus(object sender, RoutedEventArgs e)
        {
            module.SetTips(String.Empty);
            if (sender is Control && sender is Grid == false)
            {
                Control element = (Control)sender;

                element.Background = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255));
            }
        }

        void element_GotFocus(object sender, RoutedEventArgs e)
        {
            if (sender is FrameworkElement)
            {
                FrameworkElement fe = (FrameworkElement)sender;
                if (fe != null && fe.Tag != null )
                {
                    String tips = GetTips(fe.Tag.ToString());
                    module.SetTips(tips);
                }
            }
            if (sender is Control && sender is DataGrid == false && sender is DataGridColumn == false && sender is StackPanel == false)
            {
                Control element = (Control)sender;

                element.Background = new SolidColorBrush(Color.FromArgb(255, 255, 255, 0));
            }
        }

        void element_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.F12)
            {
                if (sender is TextBox)
                {
                    String TextID = String.Empty;
                    String BDColumn = String.Empty;
                    String BDTable = String.Empty;
                    String BSValueColumn = String.Empty;
                    String BSDisplayColumn = String.Empty;
                    String BSTable = String.Empty;
                    String BSColumns = String.Empty;
                    String tipsTag = String.Empty;
                    String ControlDisplayTag = String.Empty;
                    bool isAllowNull = true;

                    GetBusinessTag(((TextBox)sender).Tag.ToString(), out TextID, out BDColumn, out BDTable, out BSValueColumn, out BSDisplayColumn, out BSColumns, out BSTable, out tipsTag, out ControlDisplayTag, out isAllowNull);

                    InitSearchPopup((TextBox)sender, BSTable, searchWindow_Closed);
                }
            }

            if (e.Key == Key.Enter)
            {
                if (sender is Control)
                {
                    

                    String TextID = String.Empty;
                    String BDColumn = String.Empty;
                    String BDTable = String.Empty;
                    String BSValueColumn = String.Empty;
                    String BSDisplayColumn = String.Empty;
                    String BSTable = String.Empty;
                    String BSColumns = String.Empty;
                    String tipsTag = String.Empty;
                    String ControlDisplayTag = String.Empty;
                    bool isAllowNull = true;
                    
                    if(((Control)sender).Tag != null)
                    {
                        GetBusinessTag(((Control)sender).Tag.ToString(), out TextID, out BDColumn, out BDTable, out BSValueColumn, out BSDisplayColumn, out BSColumns, out BSTable, out tipsTag, out ControlDisplayTag, out isAllowNull);
                    }

                    if (sender is TextBox)
                    {
                        String text = ((TextBox)sender).Text;
                        if (((TextBox)sender).Tag != null)
                        {
                            if (String.IsNullOrEmpty(BSValueColumn) == false && String.IsNullOrEmpty(BSTable) == false && String.IsNullOrEmpty(ControlDisplayTag) == false)
                            {

                                if (String.IsNullOrEmpty(text) == false)
                                {

                                    FrameworkElement resultElement = GetElementByName(ControlDisplayTag);
                                    if (resultElement != null)
                                        GetDataSourceByID(resultElement, BSTable, text.Trim());
                                }
                            }
                        }
                    }

                    bool isHaveValue = false;
                    if (sender is TextBox)
                        isHaveValue = String.IsNullOrEmpty(((TextBox)sender).Text);
                    else if (sender is DatePicker)
                        isHaveValue = ((DatePicker)sender).SelectedDate != null;
                    else if (sender is ComboBox)
                        isHaveValue = ((ComboBox)sender).SelectedValue != null;

                    if (isAllowNull == true || isHaveValue == true)
                    {
                        Control nextControl = FindNextControl((Control)sender);
                        if (nextControl != null)
                        {
                            module.SetFocus(nextControl);
                        }
                    }

                }
            }
        }

        public Control FindNextControl(Control control)
        {
            int index = module.lstIndexControls.IndexOf(control);
            if (index < 0) return null;
            int iNextIndex = index + 1;
            if (module.lstIndexControls.Count > iNextIndex + 1)
                return module.lstIndexControls[iNextIndex];

            return null;
        }

        public void SetDisplayData(FrameworkElement sourceElement)
        {
            if (sourceElement is TextBox == false) return;

            String TextID = String.Empty;
            String BDColumn = String.Empty;
            String BDTable = String.Empty;
            String BSValueColumn = String.Empty;
            String BSDisplayColumn = String.Empty;
            String BSTable = String.Empty;
            String BSColumns = String.Empty;
            String tipsTag = String.Empty;
            String ControlDisplayTag = String.Empty;
            bool isAllowNull = true;

            GetBusinessTag(sourceElement.Tag.ToString(), out TextID, out BDColumn, out BDTable, out BSValueColumn, out BSDisplayColumn, out BSColumns, out BSTable, out tipsTag, out ControlDisplayTag, out isAllowNull);

            if (String.IsNullOrEmpty(BSValueColumn) == false && String.IsNullOrEmpty(BSTable) == false && String.IsNullOrEmpty(ControlDisplayTag) == false)
            {
                String text = ((TextBox)sourceElement).Text;
//                if (String.IsNullOrEmpty(text)) return;

                FrameworkElement resultElement = GetElementByName(ControlDisplayTag);
                if (resultElement != null)
                    GetDataSourceByID(resultElement, BSTable, text.Trim());
            }
        }

        public FrameworkElement GetElementByName(String Name)
        {
            FrameworkElement element = null;
            foreach (FrameworkElement item in module.lstElements)
	        {
                if(item.Name == Name)
                {
                    element = item;
                    break;
                }
	        }
            return element;
        }

        public void GetBusinessTag(String tag, out String TextID, out String BDColumn, out String BDTable, out String BSValueColumn, out String BSDisplayColumn, out String BSColumns, out String BSTable, out String tips, out String ControlDisplayTag, out bool isAllowNull)
        {
            TextID = String.Empty;
            BDColumn = String.Empty;
            BDTable = String.Empty;
            BSValueColumn = String.Empty;
            BSDisplayColumn = String.Empty;
            BSTable = String.Empty;
            BSColumns = String.Empty;
            tips = String.Empty;
            ControlDisplayTag = String.Empty;
            isAllowNull = true;

            if (String.IsNullOrEmpty(tag)) return;

            String[] arrs = tag.Split('|');

            if (arrs.Length >= 1)
                TextID = arrs[0];
            if (arrs.Length >= 2)
                BDColumn = arrs[1];
            if (arrs.Length >= 3)
                BDTable= arrs[2];
            if (arrs.Length >= 4)
                BSValueColumn = arrs[3];
            if (arrs.Length >= 5)
                BSDisplayColumn = arrs[4];
            if (arrs.Length >= 6)
                BSColumns = arrs[5];
            if (arrs.Length >= 7)
                BSTable = arrs[6];
            if (arrs.Length >= 8)
                tips = arrs[7];
            if (arrs.Length >= 9)
                ControlDisplayTag = arrs[8];
            if (arrs.Length >= 10 && String.IsNullOrEmpty(arrs[9]) == false)
                isAllowNull = false;
        }

        public String GetTips(String tag)
        {
            String tips = String.Empty;
            String[] arrs = tag.Split('|');
            if(arrs.Length >= 8)
                tips = arrs[7];

            return tips;
        }

        public String GetControlDisplayTag(String tag)
        {
            String ControlDisplayTag = String.Empty;
            String[] arrs = tag.Split('|');
            if (arrs.Length >= 9)
                ControlDisplayTag = arrs[8];

            return ControlDisplayTag;
        }

        public void SetBinding(FrameworkElement element, Object objSource, String strColumn)
        {
            DependencyProperty dp = GetDP(element);
            if (dp == null) return;

            Binding bd = new Binding(strColumn);
            bd.Source = objSource;
            bd.Mode = BindingMode.TwoWay;
            element.SetBinding(dp, bd);
        }

        public  void SetDataSource(Selector control, String strValueColumn, String strDisplayColumn, String strColumns, String strTable)
        {
            control.DisplayMemberPath = strDisplayColumn;
            control.SelectedValuePath = strValueColumn;
            DALClient client = new DALClient();
            if (strTable.Contains("_") == false)
            {
                client.GetTHE_LOAIAsync(strTable, control);
                client.GetTHE_LOAICompleted += client_GetTHE_LOAICompleted;
            }
            //else if (strTable.Equals("CA_NHAN"))
            //{
            //    client.GetCA_NHANsAsync(control);
            //    client.GetCA_NHANsCompleted += client_GetCA_NHANsCompleted;
            //}
            //else if (strTable.Equals("CONG_TY"))
            //{
            //    client.GetCONG_TYsAsync(control);
            //    client.GetCONG_TYsCompleted += client_GetCONG_TYsCompleted;
            //}
            //else if (strTable.Equals("HANG_HOA"))
            //{
            //    client.GetHang_HoasAsync(control);
            //    client.GetHang_HoasCompleted += client_GetHang_HoasCompleted;
            //}
        }

        public void GetDataSourceByID(FrameworkElement element, String strBSTable, String strID)
        {
            if (strBSTable == "CA_NHAN")
            {
                DALClient client = new DALClient();
                client.GetCA_NHANAsync(strID, element);
                client.GetCA_NHANCompleted += client_GetCA_NHANCompleted;
            }
            if (strBSTable == "CONG_TY")
            {
                DALClient client = new DALClient();
                client.GetCONG_TYAsync(strID, element);
                client.GetCONG_TYCompleted += client_GetCONG_TYCompleted;
            }
            if (strBSTable == "HANG_HOA")
            {
                DALClient client = new DALClient();
                client.GetHANG_HOAAsync(strID, element);
                client.GetHANG_HOACompleted += client_GetHANG_HOACompleted;
            }
        }

        void client_GetHANG_HOACompleted(object sender, GetHANG_HOACompletedEventArgs e)
        {
            if (e.UserState != null)
            {
                if (e.UserState is TextBox)
                {
                    if (e.Result == null)
                        ((TextBox)e.UserState).Text = String.Empty;
                    else
                        ((TextBox)e.UserState).Text = e.Result.TenHangVN;
                }
            }
        }

        void client_GetCONG_TYCompleted(object sender, GetCONG_TYCompletedEventArgs e)
        {
            if (e.UserState != null)
            {
                if (e.UserState is TextBox)
                {
                    if (e.Result == null)
                        ((TextBox)e.UserState).Text = String.Empty;
                    else
                        ((TextBox)e.UserState).Text = e.Result.TenCongTy;
                }
            }
        }

        void client_GetCA_NHANCompleted(object sender, GetCA_NHANCompletedEventArgs e)
        {
            if (e.UserState != null)
            {
                if(e.UserState is TextBox)
                {
                    if(e.Result == null)
                        ((TextBox)e.UserState).Text = String.Empty;
                    else
                        ((TextBox)e.UserState).Text = e.Result.HoTen;
                }
            }
        }

        void client_GetTHE_LOAICompleted(object sender, GetTHE_LOAICompletedEventArgs e)
        {
            if (e.UserState != null && e.UserState is Selector)
            {
                ((Selector)e.UserState).ItemsSource = e.Result;
            }
        }

        public  void SetDataSource()
        {
            ComboBox cb = new ComboBox();
            //cb.ItemS
        }

        public  DependencyProperty GetDP(FrameworkElement element)
        {
            if (element is TextBox)
                return TextBox.TextProperty;
            else if (element is DatePicker)
                return DatePicker.SelectedDateProperty;
            else if (element is ComboBox)
                return ComboBox.SelectedValueProperty;
            else if (element is Label)
                return Label.ContentProperty;
            else if (element is CheckBox)
                return CheckBox.IsCheckedProperty;

            return null;
        }

        public  void Query(String strTableName, String strQuery)
        {
            DALClient client = new DALClient();
            client.QueryAsync(strTableName, strQuery);
            client.QueryCompleted += client_QueryCompleted;
        }

        void client_QueryCompleted(object sender, QueryCompletedEventArgs e)
        {
        }

        public void InitSearchPopup(FrameworkElement element, String strTable, GenerateFunc func)
        {
            SearchWindow searchWindow = new SearchWindow(element, strTable);
            searchWindow.Show();
            searchWindow.Closed += new EventHandler(func);

            //DALClient client = new DALClient();
            //client.QueryAsync("PHIEU_NHAP", "SELECT * FROM PHIEU_NHAP");
            //client.QueryCompleted += client_QueryCompleted;

            //client.GetObjectsAsync("PHIEU_NHAP", "SELECT * FROM PHIEU_NHAP");
            //client.GetObjectsCompleted += client_GetObjectsCompleted;

            //if (strTable == "PHIEU_NHAP")
            //{
            //    client.GetReceiptsAsync();
            //    client.GetReceiptsCompleted += client_GetReceiptsCompleted;
            //}
            //else if (strTable == "CONG_TY")
            //{
            //    client.GetCONG_TYsAsync();
            //    client.GetCONG_TYsCompleted +=client_GetCONG_TYsCompleted;
            //}
            //else if (strTable == "CA_NHAN")
            //{
            //    client.GetCA_NHANsAsync();
            //    client.GetCA_NHANsCompleted +=client_GetCA_NHANsCompleted;
            //}
            //else if (strTable == "HANG_HOA")
            //{
            //    client.GetHang_HoasAsync();
            //    client.GetHang_HoasCompleted +=client_GetHang_HoasCompleted;
            //}

            //client.CloseCompleted += client_CloseCompleted;

        }

        void searchWindow_Closed(object sender, EventArgs e)
        {
            SearchWindow window = (SearchWindow)sender;

            if (window.element is TextBox)
                ((TextBox)window.element).Text = window.Value;
            else if (window.element is Label)
                ((Label)window.element).Content = window.Value;

            SetDisplayData(window.element);
        }

        public void AddElement(FrameworkElement element)
        {
            //if (GetElementByName(element.Name) == null)
            //    module.lstElements.Add(element);
        }

        //void client_GetHang_HoasCompleted(object sender, GetHang_HoasCompletedEventArgs e)
        //{
        //    SearchWindow window = new SearchWindow();
        //    window.Show();
        //    window.SearchTextBox.Focus();
        //    //window.Closed += window_Closed;
        //    window.PopulateData(e.Result, "ID,Mã số|HoTen,Họ và tên|CMND,CMND");
        //}

        //void client_GetCA_NHANsCompleted(object sender, GetCA_NHANsCompletedEventArgs e)
        //{
        //    SearchWindow window = new SearchWindow();
        //    window.Show();
        //    window.SearchTextBox.Focus();
        //    //window.Closed += window_Closed;
        //    window.PopulateData(e.Result, "ID,Mã số|TenHangVN,Tên hàng hóa|QuiCach,Quy cách");
        //}

        //void client_GetCONG_TYsCompleted(object sender, GetCONG_TYsCompletedEventArgs e)
        //{
        //    SearchWindow window = new SearchWindow();
        //    window.Show();
        //    window.SearchTextBox.Focus();
        //    //window.Closed += window_Closed;
        //    window.PopulateData(e.Result, "ID,Mã số|TenCongTy,Tên công ty|MST,MST");
        //}

        //void client_GetReceiptsCompleted(object sender, GetReceiptsCompletedEventArgs e)
        //{
        //    SearchWindow window = new SearchWindow();
        //    window.Show();
        //    window.SearchTextBox.Focus();
        //    //window.Closed += window_Closed;
        //    window.PopulateData(e.Result, "ID,Mã số|NgayLapPhieu,Ngày|DienGiai,Diễn giải");
        //}

    }
}
